// Copyright 2022 Jeroen van Nugteren

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <armadillo>
#include <algorithm>

// command line parser
#include <tclap/CmdLine.h>

// headers for common
#include "rat/common/error.hh"
#include "rat/common/log.hh"
#include "rat/common/gmshfile.hh"

// headers for distmesh
#include "distmesh2d.hh"
#include "serializer.hh"
#include "version.hh"

// main
int main(int argc, char * argv[]){
	// create tclap object
	TCLAP::CmdLine cmd("Distmesh Library",' ',rat::cmn::Extra::create_version_tag(
		DMSH_PROJECT_VER_MAJOR,DMSH_PROJECT_VER_MINOR,DMSH_PROJECT_VER_PATCH));

	// filename input argument
	TCLAP::UnlabeledValueArg<std::string> input_filename_argument(
		"if","Input filename",true, "json/geometry/moon.json", "string", cmd);
	
	// filename input argument
	TCLAP::UnlabeledValueArg<std::string> output_filename_argument(
		"of","Output filename",false, "moon.gmsh", "string", cmd);

	// parse the command line arguments
	cmd.parse(argc, argv);
	
	// get file name
	const boost::filesystem::path ifname = input_filename_argument.getValue();

	// create serialization object
	rat::dm::ShSerializerPr slzr = rat::dm::Serializer::create(ifname);

	// export
	rat::dm::ShDistMesh2DPr dmsh = slzr->construct_tree<rat::dm::DistMesh2D>(); 

	// run mesher
	dmsh->setup();

	// output to gmsh file
	if(output_filename_argument.isSet()){
		const boost::filesystem::path ofname = output_filename_argument.getValue();
		dmsh->export_gmsh(rat::cmn::GmshFile::create(ofname));
	}

	// done
	return 0;
}